#!/bin/bash

if [[ $EUID -ne 0 ]]; then echo "must be run as root"; exit 1; fi

cd `dirname $0`

# jar file
artifactId=$(xmllint --xpath "//*[local-name()='project']/*[local-name()='artifactId']/text()" pom.xml)
version=$(xmllint --xpath "//*[local-name()='project']/*[local-name()='version']/text()" pom.xml)
jar_file=$artifactId-$version.jar

# container_name
c_name=$artifactId

# image tag
img_name=$artifactId:$version

# major service module root folder
major_module=$PWD
# docker image of maven
img_mvn=maven:3.6-jdk-8-alpine
# the local maven cache dir
m2_cache=~/.m2
# the project root dir
proj_home=$PWD
build_cmd="mvn clean package -U -Dmaven.test.skip=true"
# build_cmd="mvn clean test package -U"

function build_image {
    git pull 2> /dev/null

    docker run --rm \
        -v $m2_cache:/root/.m2 \
        -v $proj_home:/usr/src/mymaven \
        -w /usr/src/mymaven \
        $img_mvn $build_cmd

    rc=$?
    if [[ $rc != 0 ]]; then
        ehoc "mvn package fail"
        exit 1
    fi

    cp "$major_module/target/$jar_file" $major_module/target/service.jar
    docker build -t ${img_name} .
}

function start_container {
    docker rm -f $c_name 2> /dev/null
    docker run -d --restart=on-failure:5 \
    --privileged=true \
    -w /home \
    -p 9000:9000 \
    -v $PWD/logs:/home/logs \
    --name $c_name $img_name \
    java \
        -Xmx250M -Xms250M -XX:MaxMetaspaceSize=100M \
        -Djava.security.egd=file:/dev/./urandom \
        -Duser.timezone=Asia/Shanghai \
        -jar /home/service.jar \
          --spring.profiles.active=prod

#        -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=19001,suspend=n \
#        -Xmx160M \
#       -Xms160M \
}

if [ "$1" == "1" ]; then
    echo build_image
    build_image
fi

echo start_container
start_container

docker logs -f $c_name